package com.example.event_resource_java.authority.server.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.event_resource_java.authority.dao.CourseClassDao.StuClassDO;
import com.example.event_resource_java.authority.dao.PaperDao.ItemPaperDao;
import com.example.event_resource_java.authority.dao.PaperDao.PracticeRecordDO;
import com.example.event_resource_java.authority.dao.StatisticDao.LearnRecordsDao;
import com.example.event_resource_java.authority.mapper.ClassMapper;
import com.example.event_resource_java.authority.mapper.ResourceMapper;
import com.example.event_resource_java.authority.mapper.StatisticMapper;
import com.example.event_resource_java.authority.server.StatisticService;
import com.example.event_resource_java.authority.server.UserServer;
import com.example.event_resource_java.commons.domain.UserDO;
import com.example.event_resource_java.commons.enums.Constants;
import com.example.event_resource_java.commons.model.ItemIdOptionBody;
import com.example.event_resource_java.commons.model.LearnTimeBody;
import com.example.event_resource_java.commons.util.ApiResult;
import com.example.event_resource_java.commons.util.DateUtils;
import com.example.event_resource_java.commons.util.JWTUtil;
import com.example.event_resource_java.commons.vo.PageResult;
import com.example.event_resource_java.commons.vo.ExamPaperVO;
import com.example.event_resource_java.commons.vo.PracticeStudentPageResult;
import com.example.event_resource_java.commons.vo.StatisticVO.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName StatisticServiceImpl
 * @Description:
 * @Author: ak
 * @CreateDate: 2024/4/22 10:03
 * @UpdateUser:
 * @UpdateDate: 2024/4/22 10:03
 * @UpdateRemark:
 * @Version: 1.0
 */
@Service
public class StatisticServiceImpl implements StatisticService {
    @Resource
    private StatisticMapper statisticMapper;

    @Resource
    private ResourceMapper resourceMapper;

    @Resource
    private ClassMapper classMapper;

    @Resource
    private UserServer userServer;

    /**
     * @auther: ak
     * @Description 班级学生练习记录
     * @param:
     * @return:
     * @date: 2024/4/23 9:04
     */
    @Override
    public PageResult list(String className, String studentName, Integer pageSize, Integer pageNum) {
        // 获取老师id
        Long createrId = JWTUtil.getUser().getId();

        PageHelper.startPage(pageNum, pageSize);
        List<PracticeRecordListVO> practiceRecordList = statisticMapper.practiceRecordList(createrId, studentName, className);
        Page<PracticeRecordListVO> page = (Page<PracticeRecordListVO>) practiceRecordList;

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * @auther: ak
     * @Description 学生个人练习记录
     * @param:
     * @return:
     * @date: 2024/4/22 17:28
     */
    @Override
    public PracticeStudentPageResult practiceRecordDetails(Long userId, Integer pageNum, Integer pageSize) {
        
        Page<PracticeRecordDetailsVO> page = new Page<>();
        // 学生查看
        if (ObjectUtil.isNull(userId)) {
            userId = JWTUtil.getUser().getId();
            //  具体学生信息
            PageHelper.startPage(pageNum, pageSize);
            List<PracticeRecordDetailsVO> detailsVOList = statisticMapper.practiceDetailList(userId, null);
            page = (Page<PracticeRecordDetailsVO>) detailsVOList;
        } else {
            // 老师查看 只返回已完成
            PageHelper.startPage(pageNum, pageSize);
            List<PracticeRecordDetailsVO> detailsVOList = statisticMapper.practiceDetailList(userId, 1);
            page = (Page<PracticeRecordDetailsVO>) detailsVOList;
        }

        UserDO userDO = classMapper.getSysUserByUserId(userId);
        return new PracticeStudentPageResult(userDO.getName(), page.getTotal(), page.getResult());
    }

    /**
     * @auther: ak
     * @Description 班级学习记录统计
     * @param:
     * @return:
     * @date: 2024/4/23 9:28
     */
    @Override
    public PageResult listLearnStatistic(String classname, String studentName, Integer pageNum, Integer pageSize) {

        // 获取老师id
        Long createrId = JWTUtil.getUser().getId();

        PageHelper.startPage(pageNum, pageSize);
        List<LearnTimeStatisticListVO> learnTimeList = statisticMapper.learnTimeList(createrId, studentName, classname);
        Page<LearnTimeStatisticListVO> page = (Page<LearnTimeStatisticListVO>) learnTimeList;

        ArrayList<LearnTimeVO> learnTimeStatisticListVOList = new ArrayList<>();
        for (LearnTimeStatisticListVO learnTimeStatisticListVO : learnTimeList) {
            Integer watchedTime = learnTimeStatisticListVO.getWatchedTime();
            Integer minute = watchedTime % 60;
            Integer hour = watchedTime / 60;
            StringBuffer sb = new StringBuffer();
            if (hour < 9 && hour > 0) {
                sb.append("0").append(hour);
            } else {
                sb.append(hour);
            }
            sb.append("小时").append(minute).append("分钟");
            LearnTimeVO learnTimeVO = new LearnTimeVO();
            BeanUtils.copyProperties(learnTimeStatisticListVO, learnTimeVO);
            learnTimeVO.setWatchedTime(sb.toString());
            learnTimeStatisticListVOList.add(learnTimeVO);
        }

        return new PageResult(page.getTotal(), learnTimeStatisticListVOList);
    }

    /**
     * @auther: ak
     * @Description 查看学生学习详情 返回根据点击分页 类型获取
     * @param:
     * @return:
     * @date: 2024/4/23 10:16
     */
    @Override
    public PageResult learnDetails(Long useId, Integer type, Integer pageNum, Integer pageSize) {
        Long evnMoId = 0L;

        if (ObjectUtil.isNull(useId)) {
            useId = JWTUtil.getUser().getId();
        }

        // 对比类型 获取资源类型
        if (type == 1) {
            // 课程资源
            evnMoId = Constants.EVENTMOID_COURSE;
        } else if (type == 2) {
            // 赛项资源
            evnMoId = Constants.EVENTMOID_COMPETITION;
        } else if (type == 3) {
            // 1+x证书资源
            evnMoId = Constants.EVENTMOID_ONEPLUSXCERTIFICATES;
        } else if (type == 4) {
            // 行业资源
            evnMoId = Constants.EVENTMOID_SECTOR;
        } else if (type == 5) {
            // 技能培训资源
            evnMoId = Constants.EVENTMOID_SKILLCULTIVATE;
        } else {
            return null;
        }

        // userId allocationId 获取资源名称 学习时间 学习时长
        PageHelper.startPage(pageNum, pageSize);
        List<LearnTimeStatisticDetailVO> learnRecordsDaoList = statisticMapper.personalLearnTimeList(useId, evnMoId);
        Page<LearnTimeStatisticDetailVO> page = (Page<LearnTimeStatisticDetailVO>) learnRecordsDaoList;

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * @auther: ak
     * @Description 更新或保存学习记录
     * @param:
     * @return:
     * @date: 2024/5/9 15:21
     */
    @Override
    public boolean saveOrUpdateLearnTime(LearnTimeBody learnTimeBody) {

        String nowTime = DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS);
        learnTimeBody.setUserId(JWTUtil.getUser().getId());

        StuClassDO stuClassDO = classMapper.getUserClassId(JWTUtil.getUser().getId());
        Long classId = stuClassDO.getClassId();

        LearnRecordsDao learnRecordsDao = statisticMapper.backup(learnTimeBody.getUserId(),
                learnTimeBody.getAllocationsId(), classId);

        // 判断是否未新增
        if (learnRecordsDao == null) {
            LearnRecordsDao learnRecords = new LearnRecordsDao();
            //userId allocationId allocationTitle watchedTime totalTime allocationsId
            //BeanUtils.copyProperties(learnTimeBody, learnRecordsDao);
            learnRecords.setUserId(learnTimeBody.getUserId());
            learnRecords.setAllocationId(learnTimeBody.getAllocationId());
            learnRecords.setAllocationTitle(learnTimeBody.getAllocationTitle());
            learnRecords.setWatchedTime(learnTimeBody.getWatchedTime());
            learnRecords.setTotalTime(learnTimeBody.getTotalTime());
            learnRecords.setLatestTime(nowTime);
            learnRecords.setAllocationsId(learnTimeBody.getAllocationsId());
            // PDF 或 观看了90%为观看完成
            if (learnTimeBody.getTotalTime() == 0 || learnTimeBody.getWatchedTime() >= (learnTimeBody.getTotalTime() * 0.9)) {
                learnRecords.setState(1);
            } else {
                learnRecords.setState(0);
            }
            learnRecords.setClassId(classId);

            return statisticMapper.saveLearnTime(learnRecords);
        }
        // 更新操作 最新观看时间 累计观看时间 是否完成
        Integer state = 0;
        if (learnTimeBody.getWatchedTime() > learnRecordsDao.getWatchedTime()) {
            learnRecordsDao.setWatchedTime(learnTimeBody.getWatchedTime());
            if (learnTimeBody.getTotalTime() == 0 || learnTimeBody.getWatchedTime() >= (learnTimeBody.getTotalTime() * 0.9)) {
                state = 1;
            }
        }
        return statisticMapper.updateLearnTime(nowTime, learnTimeBody.getWatchedTime(), state, learnTimeBody.getUserId(),
                learnTimeBody.getAllocationId(), classId, learnTimeBody.getAllocationsId());

    }

    /**
     * 视频学习记录回档
     *
     * @param allocationsId
     * @return
     */
    @Override
    public LearnRecordsDao backup(Long allocationsId) {
        if (Objects.isNull(JWTUtil.getRequest().getHeader("Authorization"))) {
            return null;
        }
        // 老师用户不记录
        Long userId = JWTUtil.getUser().getId();
        QueryWrapper<UserDO> userDOQueryWrapper = new QueryWrapper<>();
        userDOQueryWrapper.eq("id", userId);
        UserDO one = userServer.getOne(userDOQueryWrapper);
        if (one.getType() == 1) {
            return null;
        }

        StuClassDO stuClassDO = classMapper.getUserClassId(userId);
        LearnRecordsDao learnRecordsDao = statisticMapper.backup(userId, allocationsId, stuClassDO.getClassId());
        if (learnRecordsDao == null) {
            return null;
        }
        return statisticMapper.backup(userId, allocationsId, stuClassDO.getClassId());
    }

    /**
     * @auther: ak
     * @Description 获卷练习记录 取用户做题列表 获取题目返回所有试卷
     * @param:
     * @return:
     * @date: 2024/4/30 10:17
     */
    @Override
    public ExamPaperVO getExamPaper(Long practiceRecordId, Long userId) {
        // 判断是老师查看还是学生自己查询 空为学生
        if (ObjectUtil.isNull(userId)) {
            UserDO user = JWTUtil.getUser();
            userId = user.getId();
        }

        ExamPaperVO examPaperVO = new ExamPaperVO();
        PracticeRecordDO practiceRecord = resourceMapper.getContinuePracticeRecord(practiceRecordId);
        BeanUtils.copyProperties(practiceRecord, examPaperVO);
        examPaperVO.setTemplateName(practiceRecord.getPaperTitle());
        examPaperVO.setPracticeRecordId(practiceRecord.getId());

        // string转list
        JSONArray answerJson = JSON.parseArray(practiceRecord.getQuestionAnswerList());
        List<ItemIdOptionBody> questionVOList = JSONArray.parseArray(answerJson.toJSONString(), ItemIdOptionBody.class);
        // 获取题目详情 存放用户输入答案
        ArrayList<ItemPaperDao> single = new ArrayList<>();
        ArrayList<ItemPaperDao> multiple = new ArrayList<>();
        ArrayList<ItemPaperDao> judge = new ArrayList<>();
        ArrayList<ItemPaperDao> practical = new ArrayList<>();
        for (ItemIdOptionBody item : questionVOList) {
            String option = item.getValue();
            ItemPaperDao itemPaperDao = resourceMapper.questionDetail(item.getId());
            itemPaperDao.setOption(option);
            // 正确答案改变输出样式
            itemPaperDao.setRightKey(itemPaperDao.getRightKey().replaceAll(";;", ",").replaceAll(",", ""));
            // 判断题目类型
            if (itemPaperDao.getTopicTypes().equals(0)) {
                single.add(itemPaperDao);
            } else if (itemPaperDao.getTopicTypes().equals(1)) {
                multiple.add(itemPaperDao);
            } else if (itemPaperDao.getTopicTypes().equals(2)) {
                judge.add(itemPaperDao);
            } else if (itemPaperDao.getTopicTypes().equals(3)) {
                practical.add(itemPaperDao);
            }
        }

        QueryWrapper<UserDO> userDOQueryWrapper = new QueryWrapper<>();
        userDOQueryWrapper.eq("id", practiceRecord.getUserId());
        UserDO userDO = userServer.getOne(userDOQueryWrapper);

        examPaperVO.setSingle(single);
        examPaperVO.setMultiple(multiple);
        examPaperVO.setJudge(judge);
        examPaperVO.setPractical(practical);
        examPaperVO.setType(userDO.getType());
        examPaperVO.setTemplateId(practiceRecord.getPaperId());

        return examPaperVO;
    }
}
